package com.application.api;

import com.application.api.entity.ResultEntity;
import com.application.model.Message;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;

import java.util.HashMap;
import java.util.Map;

/**
 * 通知
 */
@Controller("/api/notice")
public class NoticeApiController extends BaseController {


    /*
      * 系统通知和我的消息
      */
    public void index() {

        String sel = "select * ";
        String from = " from notice where to_userid is null or to_userid = ? order by id desc ";
        Page<Message> page = Message.dao.paginate(splitPage.getPageNumber(), splitPage.getPageSize(),
                sel, from, getCUserIds());

        renderJson(new ResultEntity(page));
    }

    /*
     * 总数和最近一条内容列表
     */
    public void last(){
        String sql = "select count(1) from notice where to_userid is null or to_userid = ? and read_time is null";
        Long num = Db.queryLong(sql, getCUserIds());

        sql = "select * from notice where to_userid is null or to_userid = ? and read_time is null order by id desc";
        Message message = Message.dao.findFirst(sql, getCUserIds());

        Map<String, Object> map = new HashMap<>();
        map.put("total", num);
        map.put("data", message);

        success(map);
    }

    /*
    每条消息设置阅读时间
    param:id->xx
     */
    public void read(){
        Message message = Message.dao.findById(getPara("id"));
        if(message != null){
            message.set("read_time", getDate()).update();
            success(null);
        } else {
            error(404, "数据不存在或已被删除");
        }
    }

    /*
    html页面使用，访问系统通知。files/notice/index.html
     */
    public void view(){
        Message message = Message.dao.findById(getPara());
        success(message);
    }
}
